#include "Head.h"

void HPInit(HP* php)
{
	php->arr = NULL;
	php->capacity = php->size = 0;
}

void HPDstroy(HP* php)
{
	if (php->arr)
		free(php->arr);
	php->arr = NULL;
	php->capacity = php->size = 0;
}

void swap(HPDatatype* x, HPDatatype* y)
{
	HPDatatype ret = *x;
	*x = *y;
	*y = ret;
}  

void AdjustUp(HPDatatype* arr, int child)
{
	int parent = (child - 1 )/ 2;
	while (child > 0)
	{
		if (arr[parent] > arr[child])
		{
			swap(&arr[parent], &arr[child]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}


void HPPush(HP* php,HPDatatype x)
{
	if (php->capacity == php->size)
	{
		int newcapacity = php->capacity == 0 ? sizeof(HPDatatype) : 2 * php->capacity;
		HPDatatype* ret = (HPDatatype*)realloc(php->arr, sizeof(HPDatatype) * newcapacity);
		if (ret == NULL)
		{
			perror("realloc");
			return;
		}
		php->arr = ret;
		php->capacity = newcapacity;
	}
	php->arr[php->size] = x;
	AdjustUp(php->arr, php->size);
	php->size++;
}

int HPEmpty(HP* php)
{
	return php->size == 0;
}

void AdjustDown(HPDatatype* arr, int parent, int n)
{
	int child = parent * 2 + 1;
	while (child < n)
	{
		if (child + 1 < n && arr[child] > arr[child + 1])
		{
			child++;
		}
		if (arr[child] < arr[parent])
		{
			swap(&arr[child], &arr[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
		{
			break;
		}
	}
}

void HPPop(HP* php)
{
	assert(!HPEmpty(php));
	swap(&php->arr[php->size-1], &php->arr[0]);
	php->size--;
	AdjustDown(php->arr, 0, php->size);
}

HPDatatype HPTop(HP* php)
{
	return php->arr[0];
}